/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-03-24 20:48:40
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-03-24 22:13:48
 * @FilePath: /linux/test_3_24/roundqueue.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<pthread.h>
#include<semaphore.h>
#include<vector>
#include<unistd.h>
using namespace std;
const static int defaultnum = 5;
template<class T>
class roundqueue
{
    
    public:
    roundqueue(int cap =defaultnum):_rq(cap),_cap(cap),c_step(0),p_step(0)
    {
        sem_init(&p_sem,0,_cap);
        sem_init(&c_sem,0,0);
        pthread_mutex_init(&p_lock,nullptr);
        pthread_mutex_init(&c_lock,nullptr);
    }
    void push( T& t)
    {
        sem_wait(&p_sem);//申请信号量
        pthread_mutex_lock(&p_lock);
        _rq[p_step] = t;
        p_step++;
        p_step%=_cap;
        pthread_mutex_unlock(&p_lock);

        sem_post(&c_sem);
    }
    T pop()
    {
        sem_wait(&c_sem);
        pthread_mutex_lock(&c_lock);
        T data = _rq[c_step];
                _rq[c_step]=0;
        c_step++;
        c_step%=_cap;
        pthread_mutex_unlock(&c_lock);
        sem_post(&p_sem);
        return data;
    }
    ~roundqueue()
    {
        sem_destroy(&p_sem);
        sem_destroy(&c_sem);
        pthread_mutex_destroy(&p_lock);
        pthread_mutex_destroy(&c_lock);
    }
    private:
    vector<T> _rq;
    int _cap;
    sem_t p_sem;//生产者关注的空间剩余
    sem_t c_sem;//消费者关注的资源剩余
    pthread_mutex_t c_lock;
    pthread_mutex_t p_lock;
    int c_step;
    int p_step;
};